package com.fan.play.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.chad.library.adapter.base.BaseQuickAdapter
import java.lang.reflect.ParameterizedType

abstract class BaseBindingAdapter<T, B : ViewBinding>(data: MutableList<T>? = null) :
    BaseQuickAdapter<T, BaseBindingHolder<B>>(0, data) {
    override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): BaseBindingHolder<B> {
        val binding = initBinding(parent)
        return BaseBindingHolder(binding, binding.root)
    }

    private fun initBinding(parent: ViewGroup): B {
        val type = javaClass.genericSuperclass as ParameterizedType
        val cls = type.actualTypeArguments[1] as Class<*>
        val inflate = cls.getDeclaredMethod(
            "inflate",
            LayoutInflater::class.java,
            ViewGroup::class.java,
            Boolean::class.java
        )
        return inflate.invoke(null, LayoutInflater.from(parent.context), parent, false) as B
    }
}